package util;

/**
 * 十六进制工具类
 */
public class HexUtil {
    public static void main(String[] args) {
        System.out.println(decimalToHex(123));
        System.out.println(hexToDecimal("282CA"));
        System.out.println(Integer.toString(123, 16));
        System.out.println(Integer.toString(164554, 16));
    }

    /**
     * 10进制数转16进制字符串
     *
     * @param decimal 10进制数
     * @return 16进制字符串
     */
    public static String decimalToHex(int decimal) {
        String hex = "";
        int shang = decimal;
        int yu;
        while (shang != 0) {
            yu = shang % 16;
            shang /= 16;
            char hexBit = (char) (yu > 9 ? (yu - 10 + 'A') : (yu + '0'));
            hex = hexBit + hex;
        }
        return hex;
    }

    /**
     * 16进制字符串转10进制数
     *
     * @param hex 16进制字符串
     * @return 10进制数
     */
    public static int hexToDecimal(String hex) {
        //转换为大写
        hex = hex.toUpperCase();
        int length = hex.length();
        int decimal = 0;//10进制结果
        for (int i = 0; i < length; i++) {
            char hexBit = hex.charAt(i);//16进制位
            int decBit;//10进制位
            if (hexBit >= 'A') {
                decBit = hexBit - 'A' + 10;
            } else {
                decBit = hexBit - '0';
            }
            decimal += decBit * (int) Math.pow(16, length - i - 1);
        }
        return decimal;
    }
}
